<template>
	<!-- 固定收藏列表：分离布局，添加 touch-action -->
	<view class="main">
		<view class="navi-bar">
			<view class="navi-left" @click="naviback">
				<uni-icons type="left" color="#fff"></uni-icons>
			</view>
			<view class="navi-info" v-if="!searchMode">创建群组</view>
			<view class="navi-search" v-if="searchMode">
				<input class="search" focus placeholder-style="color:#dadada;fontSize:28rpx" confirm-type="search" @input="searchKeyword" placeholder="搜索联系人/手机号" />
			</view>
			<view class="navi-right">
				<view class="" @click="handleSearchMode">
					<uni-icons :type="searchMode ? 'closeempty' : 'search'" color="#fff"></uni-icons>
				</view>
				<view>
					<uni-icons type="map" color="#fff"></uni-icons>
				</view>
			</view>
		</view>

		<view class="selc-list" v-if="selcList.length">
			<view class="form-seleced" v-if="isSeleced">
				<view class="input-area">
					<view class="camera" @click="seleGroupPic">
						<image class="camra-pic" v-if="params.groupPicPath.length" :src="params.groupPicPath[0].tempFileURL" mode="aspectFill"></image>
						<uni-icons v-else type="camera-filled" color="#fff" size="55"></uni-icons>
					</view>
					<view class="inputName">
						<input type="text" v-model="params.groupName" placeholder="输入群名称" />
						<view class="edit-name" @click="rename">修改</view>
					</view>
				</view>
				<view class="readme">
					<text class="u-line-2">图片最多可选9张，第一张群头像,群名最多12个字</text>
				</view>
				<view class="check-group">
					<checkbox-group name="" @change="checkboxChange">
						<label>
							<checkbox :checked="false" value="needApproval" />
							<text>入群是否需要您审批</text>
						</label>
						<label>
							<checkbox :checked="true" value="visibleInRange" />
							<text>是否公开？通过本地或通过搜索是否可见</text>
						</label>
					</checkbox-group>
				</view>
				<view class="textarea">
					<textarea v-model="params.signature" placeholder="请输入群介绍（可选）" placeholder-style="color:#999;font-size:24rpx" class="custom-textarea"></textarea>
				</view>
			</view>
			<view class="selc-item" v-for="(item, index) in selcList" :key="index">
				<view class="avatar-box">
					<AvatarFallback v-if="!item.url" :name="item.name"></AvatarFallback>
					<image class="avatar" :src="item.url" mode=""></image>
				</view>
				<text class="item-text">{{ item.name }}</text>
			</view>
			<view class="surebtn" @click="seleSure">{{ isSeleced ? '再选' : '确认' }}</view>
		</view>

		<!-- 独立滚动容器：避免全局滚动冲突 -->
		<view class="scroll-container" v-if="!isSeleced" :style="{ marginTop: selcListHeight + 75 + 'px' }">
			<view class="person">
				<view class="title">
					<text>选择好友加入群聊</text>
				</view>
				<view v-if="isLoading" class="loading">加载中...</view>
				<view v-if="!isLoading && contact.length === 0" class="empty">暂无联系人</view>
				<view v-for="(person, index) in contact" :class="{ selected: isSelect(person) }" :key="index" @click="select(person)">
					<person-item :person="person"></person-item>
				</view>
			</view>
		</view>
		<view v-if="isSeleced" @click="createGroup" class="btn" :class="{ 'btn-hidden': isBtnHidden }">
			<text>创建</text>
		</view>
	</view>
</template>

<script>
// 脚本部分无需修改，保持之前修正后的代码即可
import PersonItem from '@/components/person.vue';

import AvatarFallback from '../../components/AvatarFallback.vue';
const friend = uniCloud.importObject('friend',{customUI:true});
import { Images } from '../../utils/media';
const group = uniCloud.importObject('groupManager',{customUI:true});
const linli = uniCloud.importObject('linliChat',{customUI:true});
import MessageSender from '@/utils/MessageSender.js';

export default {
	components: {
		PersonItem,
		AvatarFallback
	},
	computed: {
		storeData() {
			return this.$store.state.msg;
		}
	},
	watch: {
		selcList(newval) {
			if (newval.length > 0) {
				this.$nextTick(() => {
					this.computSelcViewHeight();
				});
			}
		}
	},
	data() {
		return {
			currentPage: 1,
			pageSize: 20,

			contact: [],
			isLoading: false,
			favoriteShow: true,
			selcListHeight: 0,
			selcList: [],
			step: 1,
			searchMode: false,
			isBtnHidden: false,
			keyword: '',
			selecedSure: false,
			debounceTimer: null,
			isSeleced: false,

			params: {
				groupName: '',
				signature: '',
				location: {},
				radius: 5,
				needApproval: false,
				visibleInRange: true,
				groupPicPath: [],
				messageSender: null,
				
			}
		};
	},
	onLoad() {
		this.messageSender = new MessageSender(this.storeData);
		this.loadContacts('');

		this.favorites = this.storeData?.user?.favorite || [];
		this.loadMe();
	},
	onReachBottom() {
		this.loadMoreContacts();
	},
	beforeDestroy() {
		if (this.params.groupPicPath.length) {
			const ids = this.params.groupPicPath.map((item) => item.fileID);
			linli.deleFile(ids);
		}
	},
	methods: {
		loadMe() {
			const me = {
				name: this.storeData.user.nicName + '(群主)' || '群主',
				url: this.storeData.user.nicPic.url || '',
				userId: this.storeData.user.userId,
				userTel:this.storeData.user.userTel
			};
			this.selcList.push(me);
		},
		search(e) {
			console.log(e);
		},
		inputValue(e) {
			console.log(e);
		},
		handleSearchMode() {
			this.searchMode = !this.searchMode;
			// 关闭搜索模式时，重置关键词并加载全部联系人
			if (!this.searchMode) {
				this.keyword = '';
				this.loadContacts('');
			}
		},
		computSelcViewHeight() {
			if (!this.selcList.length) return;
			uni.createSelectorQuery()
				.in(this)
				.select('.selc-list')
				.boundingClientRect((rect) => {
					this.selcListHeight = rect.height;
				})
				.exec();
		},
		isSelect(item) {
		return this.selcList.some((res) => res.userId === item.friendUserId);
		},
		seleSure() {
			this.isSeleced = !this.isSeleced;
			this.params.groupName = this.selcList.map((item) => item.name).join(',');
		},
		async seleGroupPic() {
			const pic = await Images();
			this.params.groupPicPath = pic;
			console.log(pic);
		},
		async loadContacts(keyword) {
			try {
				this.currentPage = 1;
				this.isLoading = true;
			const 	parma = {
					userId: this.storeData.user.userId,
					keyword: keyword,
					page: this.currentPage,
					pageSize: this.pageSize
				};
				const { success, data } = await friend.getFriendList(parma);
				if (success && data.length) {
					this.contact = data || [];
				}else{
					uni.showToast({
						title:'没有更多好友',
						position:'center'
					})
				}
			} catch (e) {
				console.error('加载通讯录失败：', e);
				uni.showToast({ title: '加载失败', icon: 'none' });
			} finally {
				this.isLoading = false;
			}
		},
		naviback() {
			uni.navigateBack();
		},
		rename() {
			this.params.groupName = '';
		},
		async loadMoreContacts(keyword) {
			if (this.isLoading) return;
			this.isLoading = true;
			try {
				const nextPage = this.currentPage + 1;
				const 	parma = {
						userId: this.storeData.user.userId,
						keyword: keyword,
						page: nextPage,
						pageSize: this.pageSize
					};
				
				
			
				const { success, data} = friend.getFriendList(parma);
				if (success && data.length > 0) {
					this.contact = [...this.contact, ...data];
					this.currentPage = nextPage;
				} else {
					uni.showToast({ title: '已加载全部', icon: 'none' });
				}
			} catch (e) {
				console.error('加载更多联系人失败：', e);
			} finally {
				this.isLoading = false;
			}
		},

		handleGroups(friends) {
			const groupMap = {};
			friends.forEach((friend) => {
				const groupId = friend.groupId || 'default';
				if (!groupMap[groupId]) {
					groupMap[groupId] = {
						groupId,
						groupName: groupId === 'default' ? '未分组' : '',
						members: []
					};
				}
				groupMap[groupId].members.push(friend);
			});
			this.groups = Object.values(groupMap);
		},

		select(person) {
			console.log('选择的人', person);
			let param = { name: '', url: '' };
			param.name = person.remarkName || person.friendDetail.nicName||person.frindUserId||'';
			param.url = person. friendDetail.nicPic?.url|| '';
			param.userId = person.friendUserId || '';
			param.userTel = person.friendUserTel || '';
			if (!param.userId && !param.userTel) {
				uni.showToast({
					title: '非法用户',
					icon: 'error'
				});
				console.error('userid和userTel至少有一个');
			}
			const idx = this.selcList.findIndex((item) => item.userId === person.friendUserId);
			if (idx !== -1) {
				this.selcList.splice(idx, 1);
			} else {
				this.selcList.push(param);
			}
		},
		searchKeyword(e) {
			console.log(e);
			const value = e.detail.value.trim();

			// 清除之前的防抖计时器
			if (this.debounceTimer) {
				clearTimeout(this.debounceTimer);
			}

			// 300ms防抖，避免频繁请求
			this.debounceTimer = setTimeout(async() => {
				const param={
					userId:this.storeData.user.userId,
					keyword:value,
					page:this.currentPage 
				}
				
			    	const res=await friend.getFriendList(param)
					if(res.success&&res.data.length){
						this.contact=res.data
					}
			}, 600);
		},
		checkboxChange(e) {
			console.log('checkbox选中状态变化：', e.detail.value);
			const selectedValues = e.detail.value || [];
			this.params.needApproval = selectedValues.includes('needApproval');
			this.params.visibleInRange = selectedValues.includes('visibleInRange');

			console.log('更新后的params：', this.params); // 打印结果，验证是否正确更新
		},
		async createGroup() {
			const userId = this.$store.state.msg.user.userId;
			try {
				if (!this.params.groupPicPath.length) {
					uni.showToast({
						title: '至少上传一张图片',
						icon: 'fail',
						duration: 2000
					});
					return;
				}
				if (!this.params.groupName) {
					uni.showToast({
						title: '群名称不能少',
						icon: 'fail',
						duration: 2000
					});
					return;
				}
                 console.log("好友列表",this.selcList);
				const groupUser = this.selcList.map((item) => ({ userId: item.userId|| '', userTel: item.userTel || '' }));
				const parmas = { ...this.params, groupUser: [...groupUser], location: this.storeData.location };

				const res = await group.createGroup(userId, parmas);
				if (res.code === 0) {
					uni.showToast({
						title: '建群成功',
						position: 'center'
					});
					const userIds = res.data.groupUser.map((item) => item.userId);
					userIds.forEach((item) => {
						const toTarget = { targetType: '3', targetId: item };
						this.messageSender.groupInvite(toTarget, res.data);
					});
					if (this.params.visibleInRang) {
						const toTarget = { targetType: '1' };
						this.messageSender.groupInvite(toTarget, res.data);
					}

					this.params = {
						groupName: '',
						signature: '',
						location: {},
						radius: 5,
						needApproval: false,
						visibleInRange: true,
						groupPicPath: []
					};
					this.isSeleced = false;
					this.selcList = [];
					uni.navigateBack();
				}
			} catch (e) {
				console.error(e);
			}
		}
	}
};
</script>

<style lang="scss" scoped>
.navi-bar {
	position: fixed;
	left: 0;
	top: 0;
	right: 0;
	z-index: 200;
	background-color: #438acc;
	height: 75rpx;
	width: 100vw;
	display: flex;
	padding-top: 90rpx;
	padding-left: 25rpx;
	padding-right: 25rpx;
	color: #fff;
	font-size: 32rpx;
	font-weight: 600;
	.navi-left {
		height: 60rpx;
	}
	.navi-info {
		flex: 1;
		height: 60rpx;
		margin-left: 25rpx;
	}
	.navi-search {
		flex: 1;
		height: 60rpx;
		margin-left: 25rpx;
		.search {
			padding: 0 10rpx;
			::placeholder {
				color: #fff !important;
				opacity: 0.8;
			}
		}
	}

	.navi-right {
		display: flex;
		height: 60rpx;
		gap: 50rpx;
		margin-right: 50rpx;
		margin-left: auto;
	}
}
.readme {
	font-size: 24rpx;
	color: #777;
}

/* 新增滚动容器样式 */
.scroll-container {
	width: 100%;
	min-height: calc(100vh - var(--selc-list-height));
	overflow-y: auto;
	-webkit-overflow-scrolling: touch;
	background-color: #fff;
}
.form-seleced {
	/* 去掉固定高度，改为自适应内容 */
	display: flex;
	flex-direction: column;
	width: 100%; /* 用100%替代固定750rpx，适配不同屏幕 */
	padding: 30rpx; /* 整体内边距，避免内容贴边 */
	gap: 25rpx; /* 元素间间距，比原来更宽松 */
	background-color: #f1f1f1;
	border-radius: 16rpx; /* 增加圆角，更美观 */
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05); /* 轻微阴影，区分层级 */

	.input-area {
		display: flex;
		align-items: center; /* 垂直居中对齐，替代flex-start */
		gap: 25rpx;
		/* 去掉固定高度，由内容撑开 */

		.camera {
			width: 120rpx;
			height: 120rpx;
			border-radius: 60rpx;
			background-color: #55aaff;
			display: flex;
			align-items: center; /* 相机图标自身居中 */
			justify-content: center;
			/* 增加轻微阴影，突出可点击感 */
			box-shadow: 0 2rpx 6rpx rgba(85, 170, 255, 0.3);
			.camra-pic {
				width: 120rpx;
				height: 120rpx;
				border-radius: 60rpx;
			}
		}

		.inputName {
			flex: 1; /* 占满剩余宽度 */
			background-color: #fff;
			border-radius: 8rpx; /* 输入框圆角 */
			padding: 0 20rpx; /* 内边距，避免文字贴边 */
			height: 80rpx; /* 固定输入框高度，保持稳定 */
			display: flex;
			align-items: center; /* 文字垂直居中 */
			.edit-name {
				width: 60rpx;
				padding: 5rpx 5rpx;
				font-size: 24rpx;
				background-color: #007aff;
				color: #fff;
				border-radius: 5rpx;
			}
			input {
				width: 100%; /* 输入框占满父容器 */
				height: 100%;
				font-size: 28rpx;
				border: none; /* 去掉默认边框 */
				background: transparent; /* 继承父容器背景 */
				::placeholder {
					color: #ccc; /* 占位符颜色更浅，区分输入状态 */
				}
			}
		}
	}

	.check-group {
		font-size: 28rpx;
		color: #666;
		display: flex;
		gap: 40rpx; /* 复选框之间间距增大，避免拥挤 */
		padding: 10rpx 0; /* 上下内边距，增加与其他元素的距离 */
		/* 去掉固定高度，由内容撑开 */
		/* 左对齐，符合表单阅读习惯 */
		justify-content: flex-start;

		label {
			display: flex;
			align-items: center;
			gap: 8rpx; /* 复选框与文字间距 */

			checkbox {
				/* 调整复选框大小 */
				transform: scale(0.8);
				margin-right: 5rpx;
			}
		}
	}

	.textarea {
		padding: 20rpx; /* 增加内边距，提升输入舒适度 */
		border-radius: 8rpx;
		font-size: 28rpx;
		background-color: #fff;
		min-height: 120rpx; /* 最小高度，避免初始状态过矮 */
		/* 去掉不必要的z-index，避免层级混乱 */

		textarea {
			width: 100%;
			height: 100%;
			min-height: 100rpx; /* 确保可输入多行 */
			border: none; /* 去掉默认边框 */
			resize: none; /* 禁止手动拉伸，保持布局稳定 */
			::placeholder {
				color: #ccc; /* 统一占位符样式 */
			}
		}
	}
}

/* 优化固定列表样式 */
.selc-list {
	position: fixed;
	left: 0;
	top: 150rpx;
	right: 0;
	display: flex;
	flex-wrap: wrap;
	gap: 12rpx;
	padding: 16rpx;
	z-index: 999;
	background-color: #fafafa;
	border-bottom: 2rpx solid rgba(0, 0, 0, 0.1);
	touch-action: none; /* 关键：禁止原生触摸行为 */
}

/* 列表项：固定高度+宽度，纵向居中，布局整齐 */
.selc-item {
	flex: 0 0 16%; /* 占比 16%，NVUE 兼容，替代 calc */
	display: flex;
	flex-direction: column;
	align-items: center; /* 子元素水平居中 */
	justify-content: center; /* 子元素垂直居中 */
	padding: 12rpx 8rpx; /* 内边距：上下12rpx，左右8rpx */
	height: 120rpx; /* 固定高度，确保所有项一致 */
	border-radius: 8rpx; /* 可选：增加圆角，更美观 */
}

/* 头像容器：固定大小，避免头像变形 */
.avatar-box {
	width: 80rpx; /* 固定宽度 */
	height: 80rpx; /* 固定高度，与头像一致 */
	overflow: hidden; /* 隐藏超出部分，避免头像溢出 */
	border-radius: 8rpx; /* 可选：头像圆角 */
}

/* 头像样式：占满容器，保持比例 */
.avatar {
	width: 100%;
	height: 100%;
}

/* 文字样式：与头像间距 5rpx，优化可读性 */
.item-text {
	font-size: 22rpx;
	color: #b6b6b6; /* 文字白色，与蓝色背景对比 */
	margin-top: 5rpx; /* 核心：头像与文字间距 5rpx */
	white-space: nowrap; /* 不换行 */
	overflow: hidden; /* 超出隐藏 */
	text-overflow: ellipsis; /* 超出显示省略号 */
	max-width: 100%; /* 限制文字宽度，避免溢出 */
	text-align: center; /* 文字居中 */
}

/* 其余原有样式不变... */
.favorite,
.group,
.person {
	padding: 10rpx 20rpx;
}
.group-title {
	display: block;
	font-size: 28rpx;
	color: #999;
	margin: 15rpx 0;
	padding-left: 10rpx;
	border-left: 4rpx solid #007aff;
}
.loading,
.empty {
	text-align: center;
	padding: 50rpx 0;
	color: #999;
}
.title {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 10rpx 35rpx;
	font-weight: 600;
	width: 92%;
	height: 60rpx;
	background-color: #e6e6e6;
}
.selected {
	border: 1rpx solid #007aff;
}
.surebtn {
	height: 80rpx;
	width: 80rpx;
	margin-right: 50rpx;
	margin-left: auto;
	border-radius: 50rpx;
	background-color: #007aff;
	display: flex;
	align-items: center;
	justify-content: center;
	color: #fff;
	font-size: 26rpx;
	align-self: center;
	justify-self: center;
}
.btn {
	position: fixed;
	right: 30rpx;
	bottom: 80rpx;
	z-index: 150;
	height: 100rpx;
	width: 100rpx;
	border-radius: 50rpx;
	background-color: #007aff;
	display: flex;
	align-items: center;
	justify-content: center;
	color: #fff;

	transition: transform 0.3s ease-out, opacity 0.3s ease-out;
	opacity: 1;
}
.btn-hidden {
	transform: translateY(200rpx);
	opacity: 0;
}
</style>
